<script setup lang="ts">
import { cancelFollow, follow, getArticledetail } from '@/services/home'
import type { ArticleDetail } from '@/types/home'
import { ref } from 'vue'
import { onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { format } from 'timeago.js'
import { showSuccessToast } from 'vant'

const route = useRoute()
const articledetail = ref<ArticleDetail>()
const loadArticledetail = async () => {
  const res = await getArticledetail(route.query.id as string)
  articledetail.value = res.data
}
onMounted(() => loadArticledetail())

const loading = ref(false)
const followOrUnfollow = async () => {
  if (!articledetail.value) return
  loading.value = true
  try {
    if (articledetail.value.is_followed) {
      await cancelFollow()
      articledetail.value.is_followed = false
      showSuccessToast('已取消关注')
    } else {
      await follow()
      articledetail.value.is_followed = true
      showSuccessToast('关注成功')
    }
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="article-page">
    <ic-nav-bar title="文章详情"></ic-nav-bar>
    <div class="detail" v-if="articledetail">
      <div class="header">
        <van-row>
          <van-col span="3">
            <van-image :src="articledetail.aut_photo" round />
          </van-col>
          <van-col span="12">
            <div class="name">{{ articledetail.aut_name }}</div>
            <div class="time">
              {{
                format(articledetail.pubdate, 'zh_CN')
                  .split(/[\t\r\f\n\s]*/g)
                  .join('')
              }}
            </div>
          </van-col>
          <van-col span="9">
            <van-button
              round
              size="small"
              @click="followOrUnfollow"
              :loading="loading"
              :class="{ active: articledetail.is_followed }"
            >
              {{ articledetail.is_followed ? '已关注' : '关注' }}
            </van-button>
          </van-col>
        </van-row>
      </div>
      <div class="body">
        <div class="title">{{ articledetail.title }}</div>
        <div class="content" v-html="articledetail.content"></div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
::v-deep(.van-button) {
  width: 64px;
  height: 26px;
  font-size: 14px;
  position: absolute;
  right: 24px;
  color: var(--ic-color2);
  background-color: #f2f3f5;
}
::v-deep(.van-image__img, .van-image__error, .van-image__loading) {
  width: 30px;
  height: 30px;
}
.active {
  color: #fff;
  background-color: var(--ic-color2);
}
.detail {
  padding: 0 24px;
  .header {
    padding: 24px 0;
    .name {
      font-size: 14px;
      line-height: 14px;
      font-weight: 500;
      margin-bottom: 4px;
    }
    .time {
      font-size: 12px;
      color: var(--ic-color3);
      line-height: 12px;
    }
  }
  .body {
    .title {
      font-size: 18px;
      line-height: 28px;
      font-weight: 500;
      margin-bottom: 8px;
    }
  }
}
</style>
